var util = require('../../utils/Hex_CRC.js');
let delayTimer = null;
let steps = 0;
Page({
    data: {
        zidongdenglu: true, //自动登录
        dengluState: false,
        peizi: true, //false为手动，true为自动
        huanjingType: -1,
        deviceId: "", //设备id
        zlValue: "",
        services: [],
        serviceId: '',
        characteristicId: {},
        characteristicIdlist: [],
        yuyue: false,
        yuyueTime: "00",
        startTime: "",
        endTime: "",
        //当前选中数组的下标值
        multiTimeIndex: [0, 0],
        multiTmieArray: [
            [],
            []
        ],

    },
    //指令输入
    binInput(e) {
        this.setData({
            zlValue: e.detail.value
        })
        // this.writeBluetoothData3(e.detail.value)
    },
    denglu() {
        if (this.data.dengluState) {
            this.closeBLEConnection()
        } else {
            let date = this.getDate(0, 0, 0, -1)
            let that = this
            that.writeBluetoothData2("01", date)
        }

    },
    chongdianzhuangstare() {
        let date = this.getDate(0, 0, 0, -1)
        // console.log(date)
        this.writeBluetoothDataState("01", date)
    },
    setPizhi() {
        this.setData({
            peizi: !this.data.peizi
        })
    },
    //  初始化选择器时间
    setTimeChange: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            multiTimeIndex: e.detail.value
        })

        let timecha = (this.hefaTime() - 14)
        console.log(timecha)
        timecha = timecha.toString(16);

        let timechalen = timecha.length % 4
        this.setData({
            timetit: '',
            yuyueTime: (timechalen === 1 ? "0" + timecha : (timechalen === 2 ? "00" + timecha : (timechalen === 3 ? "000" + timecha : (timechalen === 4 ? "0000" + timecha : timecha))))
        })
        console.log(this.data.yuyueTime)
    },

    //获取当前时间
    getDate(dateTime, hours, minutes, type) {
        var date = dateTime === 0 ? new Date() : new Date(dateTime);
        //年  
        var Y = date.getFullYear();
        //月  
        var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
        //日  
        var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
        //时  
        var h = date.getHours() + hours;
        //分  
        var m = date.getMinutes() + minutes;
        //秒
        var s = date.getSeconds()
        if (type === -1) {
            return ("" + Y).substring(2) + M + D + (h < 10 ? '0' + h : h) + (m < 10 ? '0' + m : m) + (s < 10 ? '0' + s : s)
        } else if (type === 1) {
            return Y + "/" + M + "/" + D + " " + h + ":" + m
        } else {
            return h + ":" + m
        }
    },
    //pickerc初始化时间
    getPickerDate(startTime, endTime) {
        let start_h = startTime.split(":")[0]
        let start_m = startTime.split(":")[1]
        let end_h = endTime.split(":")[0]
        let end_m = endTime.split(":")[1]
        let multiTmieArray = []
        let hList = []
        let mList = []
        if (start_h < 6) {
            for (let index = start_h; index <= end_h; index++) {
                hList.push(index + "时")
            }
        } else {
            for (let index = start_h; index <= 23; index++) {
                hList.push(index + "时")
            }
            for (let index = 0; index <= end_h; index++) {
                hList.push(index + "时")
            }
        }
        for (let index = start_m; index <= 59; index++) {
            mList.push(index + "分")
        }
        multiTmieArray.push(hList)
        multiTmieArray.push(mList)
        this.setData({
            multiTmieArray
        })
    },
    //选择Picker列
    bindTimePickerColumnChange: function (e) {
        let start_m = (this.data.startTime).split(":")[1]
        let end_m = (this.data.endTime).split(":")[1]
        let multiTmieArray = this.data.multiTmieArray
        let mList = []

        var data = {
            multiTmieArray: this.data.multiTmieArray,
            multiTimeIndex: this.data.multiTimeIndex
        };
        data.multiTimeIndex[e.detail.column] = e.detail.value;
        if (e.detail.column === 0) {
            if (data.multiTimeIndex[0] === 0) {
                for (let index = start_m; index <= 59; index++) {
                    mList.push(index + "分")
                }
            } else if (data.multiTimeIndex[0] === 18) {
                for (let index = 0; index <= end_m; index++) {
                    mList.push(index + "分")
                }
            } else {
                for (let index = 0; index <= 59; index++) {
                    mList.push(index + "分")
                }
            }

            multiTmieArray[1] = mList
            this.setData({
                multiTmieArray
            })
        }
    },

    //计算时间差
    hefaTime() {
        let start_h = (this.data.startTime).split(":")[0]
        let multiTmieArray = this.data.multiTmieArray
        let multiTimeIndex = this.data.multiTimeIndex
        let h = multiTmieArray[0][multiTimeIndex[0]].split("时")[0]
        let end_h = "";
        if (parseInt(h) < parseInt(start_h)) {
            end_h = "2022/4/19 "
        } else {
            end_h = "2022/4/18 "
        }
        start_h = "2022/4/18 " + this.data.startTime
        end_h += h + ":" + multiTmieArray[1][multiTimeIndex[1]].split("分")[0]

        let endTime = new Date(end_h).getTime()
        let startTime = new Date(start_h).getTime() - 60000

        //时间差
        let timecha = (endTime - startTime) / 1000
        return timecha
    },
    //开始充电
    startChongdian(e) {
        let that = this
        that.writeChongdian(e.currentTarget.dataset.type)
    },
    //预约充电
    yuyueChongdian(e) {
        if (e.currentTarget.dataset.type === "true") {
            let endTime = new Date().getTime() + 65535000
            let startTime = this.getDate(0, 0, 1, 0)
            this.getPickerDate(startTime, this.getDate(endTime, 0, 0, 0));
            this.setData({
                timeyuyue: this.getDate(0, 0, 1, 1),
                startTime: startTime,
                time: startTime,
                endTime: this.getDate(endTime, 0, 0, 0),
                yuyue: true
            })
        } else if (e.currentTarget.dataset.type === "false1") {
            this.setData({
                yuyue: false
            })
        } else {
            wx.showLoading({
                title: '正在预约',
                icon: 'loading',
                duration: 1000
            })
            let that = this
            that.writeChongdian("01")

            this.setData({
                yuyue: false
            })
        }
    },

    //写入执行注册指令
    writeBluetoothData0: function (result) {
        var that = this;
        let ma = this.bit216(this.toBitLength("34", 7) + this.toBitLength("01", 1)) + " " + this.bit216(this.toBitLength("01", 3) + this.toBitLength("0D", 5)) + " " + " " + result + " 00 00"

        let validation = this.crcFunction(ma)
        ma = ma + validation
        wx.writeBLECharacteristicValue({
            deviceId: that.data.deviceId,
            serviceId: that.data.serviceId,
            characteristicId: that.data.characteristicId.characteristicIdW,
            value: that.getBinaryData(ma, ma.length / 2),
            success(res) {
                console.log('writeBLECharacteristicValue success', res)
            }
        });
    },

    //写入执行(开始或预约)充电指令
    writeChongdian: function (type) {
        let that = this
        let ma = this.bit216(this.toBitLength("34", 7) + this.toBitLength("01", 1)) + this.bit216(this.toBitLength("03", 3) + this.toBitLength("03", 5)) + this.bit216(this.toBitLength(type, 3)) + (type === "00" ? "0000" : this.data.yuyueTime)
        let validation = this.crcFunction(ma)
        console.log(this.data.yuyueTime)

        ma = (ma + validation).replace(/\s+/g, "")
        console.log(ma)
        wx.writeBLECharacteristicValue({
            deviceId: that.data.deviceId,
            serviceId: that.data.serviceId,
            characteristicId: that.data.characteristicId.characteristicIdW,
            value: that.getBinaryData(ma, ma.length / 2),
            success(res) {
                console.log("发送成功")
                console.log(res)
            },
            fail(res) {
                console.log("发送失败")
                console.log(res)
            },
        });
    },

    //写入执行登陆指令
    writeBluetoothData2: function (result, timeNow) {
        let that = this
        let ma = this.bit216(this.toBitLength("34", 7) + this.toBitLength("01", 1)) + " " + this.bit216(this.toBitLength("02", 3) + this.toBitLength("07", 5)) + " " + this.bit216(this.toBitLength(result, 3)) + " " + timeNow
        let validation = this.crcFunction(ma)

        ma = (ma + validation).replace(/\s+/g, "")
        console.log("登录指令" + ma)
        wx.writeBLECharacteristicValue({
            deviceId: that.data.deviceId,
            serviceId: that.data.serviceId,
            characteristicId: that.data.characteristicId.characteristicIdW,
            value: that.getBinaryData(ma, ma.length / 2),
            success(res) {
                if (that.data.zidongdenglu) {
                    // 自动登录
                    that.setData({
                        zidongdenglu: false
                    })
                    wx.showToast({
                        title: '蓝牙登录成功',
                        duration: 3000
                    })
                }
                console.log("蓝牙登录成功")

            },
            fail(res) {
                that.setData({
                    dengluState: false
                })
                console.log("发送失败")
                console.log(res)
            },
        });
    },
    //写入执行充电桩状态指令
    chongdianzhuangstare: function (result, timeNow) {
        var that = this;
        let ma = this.bit216(this.toBitLength("34", 7) + this.toBitLength("01", 1)) + " " + this.bit216(this.toBitLength("02", 3) + this.toBitLength("07", 5)) + " " + this.bit216(this.toBitLength(result, 3)) + " " + timeNow
        let validation = this.crcFunction(ma)

        ma = (ma + validation).replace(/\s+/g, "")
        console.log(ma)
        wx.writeBLECharacteristicValue({
            deviceId: that.data.deviceId,
            serviceId: that.data.serviceId,
            characteristicId: that.data.characteristicId.characteristicIdW,
            value: that.getBinaryData(ma, ma.length / 2),
            success(res) {
                console.log("发送成功")
                wx.showToast({
                    title: '电桩状态指令成功',
                    duration: 3000
                })
            },
            fail(res) {
                console.log("电桩状态指令失败")
                console.log(res)
            },
        });
    },
    //停止充电
    dingzhichongdianBut() {
        let that = this
        that.dingzhichongdian()
    },
    //发送停止充电
    dingzhichongdian() {
        let that = this
        let ma = this.bit216(this.toBitLength("34", 7) + this.toBitLength("01", 1)) + this.bit216(this.toBitLength("04", 3) + this.toBitLength("00", 5))
        let validation = this.crcFunction(ma)
        ma = (ma + validation).replace(/\s+/g, "")
        wx.writeBLECharacteristicValue({
            deviceId: that.data.deviceId,
            serviceId: that.data.serviceId,
            characteristicId: that.data.characteristicId.characteristicIdW,
            value: that.getBinaryData(ma, ma.length / 2),
            success(res) {
                console.log("发送成功")
                console.log(res)
            },
            fail(res) {
                console.log("发送失败")
                console.log(res)
            },
        });
    },
    //执行测试指令
    writeBluetoothDataTest() {
        let that = this
        that.writeBluetoothData3()
    },
    writeBluetoothData3: function () { //写入执行指令
        let that = this
        let ma = that.data.zlValue
        wx.writeBLECharacteristicValue({
            deviceId: that.data.deviceId,
            serviceId: that.data.serviceId,
            characteristicId: that.data.characteristicId.characteristicIdW,
            value: that.getBinaryData(ma, ma.length / 2),
            success(res) {
                console.log("发送成功")
                console.log(res)
            },
            fail(res) {
                console.log("发送失败")
                console.log(res)
            },
        });
    },
    getBinaryData: function (message, len) { //将数据转为二进制数组
        let buffer = new ArrayBuffer(len);
        let dataView = new DataView(buffer);
        var numTitle = 0;
        for (var i = 0; i < message.length; i = i + 2) {
            var numStr16 = message.substr(i, 2);
            var num = parseInt(numStr16, 16);
            dataView.setUint8(numTitle, num);
            numTitle++;
        }
        return buffer;
    },
    //计算指令
    jishuanzhilin() {
        let ma = this.bit216(this.toBitLength("34", 7) + this.toBitLength("01", 1)) + " " + this.bit216(this.toBitLength("04", 3) + this.toBitLength("00", 5))
        let validation = this.crcFunction(ma)
        // .replace(/\s+/g,"")
        console.log((ma + validation))
    },
    setCharacteristicId(e) {
        let uuid = e.currentTarget.dataset.uuid
        let characteristicId = this.data.characteristicId
        switch (this.data.huanjingType) {
            case '0':
                characteristicId.characteristicIdR = uuid
                break;
            case '1':
                characteristicId.characteristicIdW = uuid
                break;
            default:
                break;
        }
        this.setData({
            characteristicId
        })
    },
    sethuanjing(e) {
        if (!this.data.peizi) { //false为手动，true为自动
            this.setData({
                huanjingType: e.currentTarget.dataset.type
            })
        }
    },
    getserviceIdBut(e) {
        let uuid = e.currentTarget.dataset.uuid
        this.setData({
            serviceId: uuid
        })
        this.getserviceId()
    },
    getserviceId() {
        let serviceId = this.data.serviceId
        let services = this.data.services
        if (this.data.peizi) { //false为手动，true为自动
            serviceId = services[1].uuid
            for (let index = 0; index < services.length; index++) {
                if (services[index].uuid.indexOf('00001000') != -1) {
                    serviceId = (services[index].uuid)
                    break;
                }
            }
            this.setData({
                serviceId
            })
        }
        this.shujujiaohu(serviceId);
    },
    ab2hex: function (buffer) { //将二进制数组进行转换
        var hexArr = Array.prototype.map.call(
            new Uint8Array(buffer),
            function (bit) {
                return ('00' + bit.toString(16)).slice(-2)
            }
        )
        return hexArr.join('');
    },
    //对消息内容bit分割还原转换
    toBitto16(int16, arrLen) {
        let i2 = parseInt(int16, 16).toString(2) //长度没有超过13位
        let to16 = ''
        switch ((i2.length) % 4) {
            case 0:
                break;
            case 1:
                i2 = '000' + i2
                break;
            case 2:
                i2 = '00' + i2
                break;
            case 3:
                i2 = '0' + i2
                break;
        }
        console.log(i2)
        for (let i = 0; i < arrLen.length - 1; i++) {
            to16 += parseInt((i2.substring(arrLen[i], arrLen[i] + arrLen[i + 1])), 2).toString(16) + ','
        }
        return to16
    },


    // 字符串转16进制
    strToHexCharCode(str) {
        if (str === "")
            return "";
        var hexCharCode = [];
        // 　　hexCharCode.push("0x");
        for (var i = 0; i < str.length; i++) {
            hexCharCode.push((str.charCodeAt(i)).toString(16));
        }
        return hexCharCode.join("");
    },

    //crc效验
    crcFunction(buffer) {
        let CS_B = util.crc16(buffer).split(" ");
        return " " + CS_B[1] + " " + CS_B[0]
    },
    //对消息内容bit转换
    toBitLength(int16, intlen) {
        let i2 = parseInt(int16, 16).toString(2) //长度没有超过13位
        let i16to2 = i2
        if (i2.length < intlen) {
            for (let i = 0; i < intlen - i2.length; i++) {
                i16to2 = "0" + i16to2;
            }
        } else if (i2.length > intlen) {
            i16to2 = i2.substring(0, i2.length - (i2.length - intlen))
        }

        return i16to2
    },
    //对消息内容转换
    bit216(bitto16) {
        let int16 = parseInt(bitto16, 2).toString(16);

        int16 = int16.length % 2 === 0 ? int16 : "0" + int16

        return int16;
    },
    onLoad() {
        var that = this;
        console.log("启动蓝牙适配器, 蓝牙初始化")
        wx.openBluetoothAdapter({ //初始化蓝牙模块
            success: (res) => {
                console.log("打开蓝牙成功.")
                that.startBluetoothDevicesDiscovery(); //开始搜索蓝牙设备
            },
            fail: (res) => {
                console.log("------初始化蓝牙模块失败！！------");
                wx.showLoading({
                    title: '请打开蓝牙',
                    icon: 'loading',
                    duration: 3000
                })
            }
        });
    },

    //当退出页面，断开蓝牙连接
    onUnload() {
        wx.closeBLEConnection({
            deviceId: this.data.deviceId,
            success(res) {}
        })
    },

    //开始搜索附近蓝牙设备   
    startBluetoothDevicesDiscovery() {
        if (steps === 1) {
            this.closeBLEConnection()
        }
        var that = this
        wx.startBluetoothDevicesDiscovery({

            allowDuplicatesKey: false,

            interval: 0,

            success: function (res) {

                wx.showLoading({

                    title: '正在搜索设备',

                })
                console.log("startBluetoothDevicesDiscovery:", res);

                delayTimer = setInterval(function () {
                    that.discoveryBT() //3.0 //这里的discovery需要多次调用
                    console.log("delayTimer:" + delayTimer)
                }, 1000);

                setTimeout(function () {
                    if (!that.data.deviceId) {

                        wx.hideLoading();
                        console.log("搜索设备超时");

                        wx.stopBluetoothDevicesDiscovery({

                            success: function (res) {

                                console.log('连接蓝牙成功之后关闭蓝牙搜索');

                            }

                        })
                        clearInterval(delayTimer)
                        wx.showModal({

                            title: '搜索设备超时',

                            content: '请检查蓝牙设备是否正常工作，Android手机请打开GPS定位.',

                            showCancel: false

                        })
                        wx.stopBluetoothDevicesDiscovery({}); //关闭搜索
                        wx.closeBluetoothAdapter({}); //关闭蓝牙模块
                        console.log("搜索设备超时，请打开GPS定位，再搜索")
                    }
                }, 15000);

            },

            fail: function (res) {
                wx.showToast({
                    title: '设备发现失败',
                    duration: 3000
                })
                console.log("蓝牙设备服务发现失败: " + res.errMsg);

            }

        })
    },

    discoveryBT: function () {

        var that = this

        wx.getBluetoothDevices({

            success: function (res) {

                var list = res.devices;
                console.log(res)
                if (list.length <= 0) {

                    return;

                }

                var devices = [];
                let RSSI_d = [];
                for (var i = 0; i < list.length; i++) {

                    //所以我去遍历我搜索到的蓝牙设备中是否有这个ID

                    var name = list[i].name || list[i].localName;

                    console.log("name:", name + " RSSI:" + list[i].RSSI)

                    if (name == "sn" || name.substring(0, 5) === "CCEVC") {
                        devices.push(list[i]);
                    } else {
                        continue;
                    }

                }

                let RSSI = devices[0];
                for (let x = 0; x < devices.length; x++) {
                    RSSI = RSSI < devices[x] ? devices[x] : RSSI
                }
                RSSI_d.push(RSSI);
                console.log('总共有' + devices.length + "个设备需要设置")

                if (devices.length <= 0) {

                    return;

                }
                console.log(RSSI_d)
                steps = 1
                clearInterval(delayTimer)
                that.callback(RSSI_d)
            },

            fail: function () {
                wx.showToast({
                    title: '搜索蓝牙设备失败',
                    duration: 3000
                })

            }

        })

    },

    callback(res) { //新搜索到设备的回调函数
        var deviceObj = res[0];
        console.log("连接蓝牙设备");
        wx.stopBluetoothDevicesDiscovery({}); //关闭搜索
        this.setData({
            deviceId: deviceObj.deviceId
        }); //存储目标蓝牙设备id
        this.connectBLEDevice(); //去连接蓝牙设备
    },

    connectBLEDevice: function () { //连接低功耗蓝牙设备
        var that = this;
        var deviceId = that.data.deviceId;
        wx.showLoading({
            title: '正在连接设备',
        })
        console.log("正在连接设备")
        wx.createBLEConnection({
            deviceId: deviceId,
            success: (res) => { //连接蓝牙设备成功
                wx.showToast({
                    title: '蓝牙连接成功',
                    duration: 3000
                })
                wx.getBLEDeviceServices({
                    deviceId: that.data.deviceId,
                    success(res) { //获取服务id成功
                        console.log(res)
                        let services = res.services
                        that.setData({
                            services
                        });
                        //自动登录
                        that.setData({
                            zidongdenglu: true
                        })
                        that.getserviceId()
                    }
                })
            },
            fail: (res) => {
                wx.showToast({
                    title: '蓝牙连接超时',
                    duration: 3000
                })
                console.log("连接蓝牙设备失败");
                console.log(res);
            }
        });
    },

    //获取通道characteristicId
    shujujiaohu(serviceId) { //type为为写，false为读
        let that = this
        wx.getBLEDeviceCharacteristics({
            deviceId: that.data.deviceId,
            serviceId: serviceId,
            success(res) { //获取特性值id成功
                console.log(res)
                let characteristicIdlist = res.characteristics
                let characteristicId = that.data.characteristicId
                for (let index = 0; index < characteristicIdlist.length; index++) {
                    if (characteristicIdlist[index].properties.write === true && characteristicIdlist[index].properties.read === true) {
                        characteristicId.characteristicIdW = characteristicId.hasOwnProperty('characteristicIdW') ? characteristicId.characteristicIdW : characteristicIdlist[index].uuid
                    } else if (characteristicIdlist[index].properties.notify === true && characteristicIdlist[index].properties.read === true) {
                        characteristicId.characteristicIdR = characteristicId.hasOwnProperty('characteristicIdR') ? characteristicId.characteristicIdR : characteristicIdlist[index].uuid
                    }
                }
                that.setData({
                    characteristicId,
                    characteristicIdlist
                });

                if (that.data.zidongdenglu) {
                    // 自动登录
                    console.log("自动登录" + that.data.zidongdenglu)
                    that.notifyBLECharacteristicValueChange()
                }
            }
        })
    },
    hex2int(hex) {
        var len = hex.length,
            a = new Array(len),
            code;
        for (var i = 0; i < len; i++) {
            code = hex.charCodeAt(i);
            if (48 <= code && code < 58) {
                code -= 48;
            } else {
                code = (code & 0xdf) - 65 + 10;
            }
            a[i] = code;
        }
        return a.reduce(function (acc, c) {
            acc = 16 * acc + c;
            return acc;
        }, 0);
    },
    //回调指令判断
    toNotifyBLE(e) {
        let ma = e.replace(/\s+/g, "")
        let ma_i = ma.substring(2, 4)
        if ((this.bit216(this.toBitLength("02", 3) + this.toBitLength("0D", 5))) === ma_i) {
            this.denglu()
            //准备登录

        } else if ((this.bit216(this.toBitLength("03", 3) + this.toBitLength("01", 5))) === ma_i) {
            let result = ma.substring(4, 6)
            wx.showToast({
                title: (result === '01' ? '充电成功' : (result === '02' ? '设备故障' : (result === '99' ? '其它错误' : '未知问题'))),
                duration: 3000
            })
        } else if ((this.bit216(this.toBitLength("04", 3) + this.toBitLength("01", 5))) === ma_i) {
            let result = ma.substring(4, 6)
            wx.showToast({
                title: (result === '01' ? '断电成功' : (result === '02' ? '断电失败' : (result === '99' ? '其它错误' : '未知问题'))),
                duration: 3000
            })
        } else if ((this.bit216(this.toBitLength("05", 3) + this.toBitLength("0D", 5))) === ma_i) {

            this.setData({
                chongdianzhuangdata: "电流：" + (this.hex2int((ma.substring(4, 8))) * 0.1) + "A  电压—" + (this.hex2int((ma.substring(8, 12))) * 0.1) + "V  功率—" + this.hex2int((ma.substring(12, 16))) + "W  充电电量—" + (this.hex2int((ma.substring(16, 20))) * 0.001) + "kWh  充电时长—" + this.hex2int((ma.substring(20, 24))) + "秒  充电费用—" + this.hex2int((ma.substring(24, 28))) + "分  温度—" + this.hex2int((ma.substring(28, 30))) + "分"
            })
        } else if ((this.bit216(this.toBitLength("06", 3) + this.toBitLength("03", 5))) === ma_i) {
            let result = ma.substring(4, ma.length - 4)
            let data = ''
            for (let index = 0; index <= result.length / 4; index++) {
                const element = result.substring(index * 4, (index + 1) * 4)
                const chargeStatus = element.substring(0, 2)
                const plugStatus = element.substring(2, 4)
                data += (index + "号桩状态:" + (chargeStatus === '00' ? '空闲' : (chargeStatus === '01' ? '充电中' : (chargeStatus === '02' ? '预约' : (chargeStatus === '03' ? '故障' : '未知')))) + '—' + index + "号枪状态:" + (plugStatus === '00' ? '未插枪' : (plugStatus === '01' ? '插枪未充电' : (plugStatus === '02' ? '插枪充电中' : '未知')))+" ")
            }
            this.setData({
                chongdianzhuangstate: data+ma
            })
        }
    },
    //消息回调
    notifyBLECharacteristicValueChange() {
        var that = this;
        console.log('6.启用低功耗蓝牙设备特征值变化时的 notify 功能')
        wx.notifyBLECharacteristicValueChange({
            state: true,
            deviceId: that.data.deviceId,
            serviceId: that.data.serviceId,
            characteristicId: that.data.characteristicId.characteristicIdR,
            complete(res) {
                /*用来监听手机蓝牙设备的数据变化*/
                wx.onBLECharacteristicValueChange(function (res) {
                    console.log("ab2hex：" + that.ab2hex(res.value))
                    that.toNotifyBLE(that.ab2hex(res.value))
                    // console.log("buf2string："+that.buf2string(res.value))
                    // console.log("receiveData"+that.receiveData(res.value))

                })
            },
            fail(res) {
                console.log(res, '启用低功耗蓝牙设备监听失败')
            }
        })
    },
    closeBLEConnection: function () { //断开与低功耗蓝牙设备的连接
        var that = this;
        wx.closeBLEConnection({
            deviceId: that.data.deviceId,
            success: (res) => {
                steps = 0
                that.setData({
                    dengluState: false
                })
                wx.showToast({
                    title: '已断开连接',
                    duration: 3000
                })
            }
        });
    },
    /*转换成需要的格式*/
    buf2string(buffer) {
        var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
        return arr.map((char, i) => {
            return String.fromCharCode(char);
        }).join('');
    },
    receiveData(buf) {
        return this.hexCharCodeToStr(this.ab2hex(buf))
    },
    /*转成可展会的文字*/
    hexCharCodeToStr(hexCharCodeStr) {
        var trimedStr = hexCharCodeStr.trim();
        var rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr;
        var len = rawStr.length;
        var curCharCode;
        var resultStr = [];
        for (var i = 0; i < len; i = i + 2) {
            curCharCode = parseInt(rawStr.substr(i, 2), 16);
            resultStr.push(String.fromCharCode(curCharCode));
        }
        return resultStr.join('');
    },
    onShareAppMessage: function (res) {

    }
});